package com.appspot.simplebookmarks.service;

import java.util.List;

import org.slim3.datastore.Datastore;

import com.appspot.simplebookmarks.meta.BookmarkMeta;
import com.appspot.simplebookmarks.model.Bookmark;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;


public class BookmarkService {

    public Bookmark add(Bookmark bookmark) {
        Integer displayOrder = 
            this.getLastOrderNumber(bookmark.getAuthor(), bookmark.getCollectionKey());
        bookmark.setDisplayOrder(displayOrder + 1);
        Transaction tx = Datastore.beginTransaction();
        Datastore.put(bookmark);
        tx.commit();
        return bookmark;
    }

    private Integer getLastOrderNumber(String author, Key collectionKey) {
        List<Bookmark> b = this.getList(author, collectionKey);
        if (b.size() == 0) {
            return 0;
        }
        return b.get(b.size() - 1).getDisplayOrder();
    }

    public List<Bookmark> getList(String author, Key collectionKey) {
        BookmarkMeta e = BookmarkMeta.get();
        return  Datastore.query(e)
            .filter(e.author.equal(author))
            .filter(e.collectionKey.equal(collectionKey))
            .sort(e.displayOrder.asc)
            .asList();
    }
}
